Passed
Push — main ( 7025c8...8c0a07 )
by Bjarn
03:07 queued 01:44
created

SubdomainController   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 106
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 74
dl 0
loc 106
rs 10
c 0
b 0
f 0
wmc 13

4 Functions

Rating   Name   Duplication   Size   Complexity  
A addSubdomain 0 24 3
A subdomainExists 0 6 2
A deleteSubdomain 0 25 3
A execute 0 21 5
1
import {readFileSync, writeFileSync} from 'fs'
2
import Nginx from '../services/nginx'
3
import {getConfig, jaleSitesPath} from '../utils/jale'
4
5
class SubdomainController {
6
7
    serverNamesRegex = new RegExp('(?<=server_name \\s*).*?(?=\\s*;)', 'gi')
8
9
    execute = async (option: string, subdomain: string): Promise<void> => {
10
        if (option !== 'add' && option !== 'del') {
11
            console.log('Invalid option. Please use \'add\' or \'del\', followed by the subdomain.')
12
            return
13
        }
14
15
        const config = await getConfig()
16
        const project = process.cwd().substring(process.cwd().lastIndexOf('/') + 1)
17
        const hostname = `${project}.${config.domain}`
18
19
        let restartNginx = false
20
21
        if (option === 'add') {
22
            restartNginx = this.addSubdomain(subdomain, hostname)
23
        }
24
        else if (option === 'del') {
25
            restartNginx = this.deleteSubdomain(subdomain, hostname)
26
        }
27
28
        if (restartNginx)
29
            await (new Nginx()).reload()
30
    }
31
32
    /**
33
     * Check if the subdomain already exists in the vhost's Nginx configuration.
34
     *
35
     * @param subdomain
36
     * @param hostname
37
     */
38
    subdomainExists = (subdomain: string, hostname: string): boolean => {
39
        try {
40
            const vhostConfig = readFileSync(`${jaleSitesPath}/${hostname}.conf`, 'utf-8')
41
            return vhostConfig.includes(`${subdomain}.${hostname}`)
42
        } catch (e) {
43
            return false
44
        }
45
    }
46
47
    /**
48
     * Add a new subdomain to the vhost's Nginx configuration.
49
     *
50
     * @param subdomain
51
     * @param hostname
52
     */
53
    addSubdomain = (subdomain: string, hostname: string): boolean => {
54
        if (this.subdomainExists(subdomain, hostname)) {
55
            console.log(`Subdomain ${subdomain}.${hostname} already exists.`)
56
            return false
57
        }
58
59
        let vhostConfig = readFileSync(`${jaleSitesPath}/${hostname}.conf`, 'utf-8')
60
        const rawServerNames = this.serverNamesRegex.exec(vhostConfig)
61
62
        if (!rawServerNames) {
63
            return false // TODO: Catch this issue
64
        }
65
66
        const serverNames = rawServerNames[0].split(' ')
67
        serverNames.push(`${subdomain}.${hostname}`)
68
69
        // Replace the old server names with the server names including the new subdomain.
70
        vhostConfig = vhostConfig.replace(this.serverNamesRegex, serverNames.join(' '))
71
72
        writeFileSync(`${jaleSitesPath}/${hostname}.conf`, vhostConfig)
73
74
        console.log(`Added subdomain ${subdomain}.${hostname}`)
75
76
        return true
77
    }
78
79
    /**
80
     * Delete a subdomain from the vhost's Nginx configuration.
81
     *
82
     * @param subdomain
83
     * @param hostname
84
     */
85
    deleteSubdomain = (subdomain: string, hostname: string): boolean => {
86
        if (!this.subdomainExists(subdomain, hostname)) {
87
            console.log(`Subdomain ${subdomain}.${hostname} does not exist.`)
88
            return false
89
        }
90
91
        let vhostConfig = readFileSync(`${jaleSitesPath}/${hostname}.conf`, 'utf-8')
92
93
        const rawServerNames = this.serverNamesRegex.exec(vhostConfig)
94
95
        if (!rawServerNames) {
96
            return false // TODO: Catch this issue
97
        }
98
        
99
        const serverNames = rawServerNames[0].split(' ')
100
        serverNames.splice(serverNames.indexOf(`${subdomain}.${hostname}`), 1)
101
102
        // Replace the old server names with the new list without the removed subdomain.
103
        vhostConfig = vhostConfig.replace(this.serverNamesRegex, serverNames.join(' '))
104
105
        writeFileSync(`${jaleSitesPath}/${hostname}.conf`, vhostConfig)
106
107
        console.log(`Removed subdomain ${subdomain}.${hostname}`)
108
109
        return true
110
    }
111
112
}
113
114
export default SubdomainController